package com.yuven.appframework.network.interceptor

import android.webkit.WebSettings
import com.yuven.baselib.utils.ToolsKit
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.*

/**
 * 
 * 通用Header封装
 * @author :        Yuven
 * @date :          5/21/21 9:17 AM
 * @desc :
 */
class HeaderInterceptor : Interceptor {

    private var userAgent = ""

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val original: Request = chain.request()
        if (userAgent.isEmpty()) {
            userAgent = getUserAgent()
        }
        //通用请求头
        val requestBuilder: Request.Builder = original.newBuilder()
            .removeHeader("User-Agent") //移除旧的UserAgent
            .addHeader("User-Agent", userAgent) //添加新的UserAgent
            .addHeader("Content-Type", "application/json;charset=utf-8")
        val request: Request = requestBuilder.build()
        return chain.proceed(request)
    }

    private fun getUserAgent(): String {
        val userAgent = try {
            WebSettings.getDefaultUserAgent(ToolsKit.getClient())
        } catch (e: Exception) {
            System.getProperty("http.agent")
        }
        val sb = StringBuffer()
        var i = 0
        val length = userAgent.length
        while (i < length) {
            val c = userAgent[i]
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", c.code))
            } else {
                sb.append(c)
            }
            i++
        }
        return sb.toString()
    }

}